<template>
<div class="user-notice">

  <div class="user-menu">
    <el-menu default-active="0" class="el-menu-vertical-demo" @select="selectHandle" :collapse="true">

      <el-menu-item v-for="(item,indexItem) in messageTitle" :key="item" :index="indexItem.toString()">
        <el-badge  :is-dot="(indexItem>=1 && isRead[indexItem-1]>0)>0" class="item">{{item}}</el-badge>
<!--        <span v-else-if="indexItem<=1 || !isRead[indexItem]">{{item}}</span>-->
      </el-menu-item>

    </el-menu>

  </div>
  <div class="user-menu-detail">
    <div class="user-mail-header">
      <span style="font-weight: 600">{{ messageTitle[idx] }}</span>
      <span style="float: right">共 {{ total }} 条</span>
    </div>
    <div class="user-mail-list">

<!--      我的发布-->
      <div v-if="idx==0" >
        <div style="margin-top: 25px;margin-bottom: 20px;" v-show="total>0">
          <el-radio-group v-model="params.type" @change="chg(1)">
            <el-radio  :label="''">全部</el-radio>
            <el-radio  label="0">只看帖子</el-radio>
            <el-radio label="1">只看评论</el-radio>
            <el-radio label="2">只看回复</el-radio>
          </el-radio-group>

        </div>
        <div v-for="item in myCommentList" :key="item.id">
<!--          标题-->
          <div style="font-weight: 300;margin-bottom: 10px;margin-top: 20px;">
            发布了<span>{{item.type==0?"帖子":"评论"}}</span>：
            <a v-if="item.type==0" style="color: #c177e8" href="javascript:void(0)" @click="$router.push('/main/comment/detail/'+item.id)">{{ item.title }}</a>
            <a v-if="item.type!=0" style="color: #c177e8" href="javascript:void(0)" @click="$router.push('/main/comment/detail/'+item.root.id)">{{ item.root.title }}</a>
            <span class="user-mail-time">{{ $MyUtils.timeToString(item.createTime) }}</span>
            <a href="javascript:void(0)" @click="deleteComment(item)" class="user-mail-time"><i class="el-icon-delete"></i> 删除</a>

          </div>
          <mavonEditor  :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
                       v-model="item.text" style="max-height: 120px;min-height:70px;margin-right: 30px;"/>
<!--          <div v-if="item.type==2" style="max-height: 30px;margin-right: 30px;">{{item.text}}</div>-->
        </div>

      </div>
<!--      系统消息-->
      <div v-if="idx==1" >
        <div v-for="item in systemMail" :key="item.id">
          <div style="font-weight: 300;margin-bottom: 10px;margin-top: 20px;">{{ item.title }}
            <span class="user-mail-time">{{ $MyUtils.timeToString(item.createTime) }}</span>
            <a href="javascript:void(0)" @click="deleteMail(item)" class="user-mail-time"><i class="el-icon-delete"></i> 删除</a>
          </div>
          <mavonEditor :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
                       v-model="item.text" style="min-height: 30px;margin-right: 30px;"/>
        </div>

      </div>
<!--      评论-->
      <!--      回复-->
      <div v-if="idx==2||idx==3" >
        <div v-for="item in CommentList" :key="item.id">
          <div style="font-weight: 300;margin-bottom: 10px;margin-top: 20px;">
            <a href="javascript:void(0)" style="color: #c177e8" @click="$router.push('/main/user/detail/'+item.userId)" v-html="userNames[item.userId]"></a>

            <span v-if="idx==2">
                 评论了<a style="color: #c177e8" href="javascript:void(0)" @click="$router.push('/main/comment/detail/'+item.fatherId)"> 帖子</a>
            </span>
            <span v-if="idx==3">
              回复了你在 <a v-if="item.root" style="color: #25bb9b" @click="$router.push('/main/comment/detail/'+item.root.id)" href="javascript:void(0)" :disabled="item.root.status!=0">{{item.root.title}}</a> 中的评论
            </span>
            <span class="user-mail-time">{{ $MyUtils.timeToString(item.createTime) }}</span>
          </div>
          <mavonEditor :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
                       v-model="item.text" style="min-height: 30px;margin-right: 30px;"/>
        </div>

      </div>
<!--      私信消息-->
      <div v-if="idx==4">
        <div style="margin-top: 25px;margin-bottom: 20px;" >
          <el-radio-group v-model="params.type" @change="changeSendReply">
            <el-radio  :label="0">收件箱</el-radio>
            <el-radio :label="1">已发送</el-radio>
          </el-radio-group>

        </div>
        <div class="block">
          <el-timeline>
            <el-timeline-item v-for="item in myMailList" :key="item.date" :timestamp="item.date" placement="top">
              <a href="javascript:void(0)" @click="mailDetailClick(item1)" v-for="item1 in item.list" :key="item1.id" class="notice-mail-list" >
                <span style="width: 3%;"><i :style="item1.read==0?'color: #e5a92b':''" :class="item1.read==0?' fa fa-envelope-o':'fa fa-envelope-open-o'"></i></span>
                <span v-if="params.type==0" style="width: 11%;">{{userNames[item1.userId].substring(0,10)}}{{userNames[item1.userId].length>10?'...':''}}</span>
                <span v-if="params.type==1" style="width: 11%;">{{userNames[item1.to].substring(0,10)}}{{userNames[item1.to].length>10?'...':''}}</span>
                <span style="width: 75%;">{{(item1.title?item1.title:"").substring(0,20)}} <span style="color: #9f9f9f;"> - {{item1.text?item1.text.substring(0,20):''}}</span></span>
                <span style="width: 10%;font-size: 14px;">{{$MyUtils.timeToString((item1.createTime))}}</span>
              </a>
            </el-timeline-item>

          </el-timeline>
        </div>

      </div>



      <div style="text-align: right;margin-top: 20px;margin-bottom: 10px;"  v-show="total>0">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="params.size"
            @current-change="chg" >
        </el-pagination>

      </div>
      <el-empty  v-show="total==0" description="空空如也"></el-empty>
    </div>
</div>

<!--  详细信息弹框-->
  <el-dialog
      :title="mailDetail.title"
      :visible.sync="mailFlag">
    <div style="color: grey;">
      发送人: <a href="javascript:void(0)" style="color: #c177e8" @click="$router.push('/main/user/detail/'+mailDetail.userId)" v-html="userNames[mailDetail.userId]"></a>
    </div>
    <div style="color: grey;margin-top: 10px;">
      收件人: <a href="javascript:void(0)" style="color: #c177e8" @click="$router.push('/main/user/detail/'+mailDetail.to)" v-html="userNames[mailDetail.to]"></a>
    </div>
    <div style="color: grey;margin-top: 10px;">
      时 &nbsp;&nbsp;&nbsp;间: {{$MyUtils.timeToString(mailDetail.createTime)}}
    </div>
    <hr/>
    <div>{{mailDetail.text}}</div>

    <span slot="footer" class="dialog-footer">
    <el-button @click="mailFlag = false">取 消</el-button>
    <el-button type="primary" v-show="this.params.type==0" @click="mailFlag = false;replyFlag = true;">回 复</el-button>
    </span>
  </el-dialog>

<!--  发送私信弹框-->
  <el-dialog title="发送私信" :visible.sync="replyFlag">
    <el-form :model="replyText"  label-width="80px" style="text-align: left">
      <el-form-item label="发给">
        <span v-html="userNames[mailDetail.userId]"></span>
        <el-input v-model="replyText.to" autocomplete="off" v-show="false"></el-input>
      </el-form-item>
      <el-form-item label="主题">
        <el-input v-model="replyText.title"  maxlength="20" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input type="textarea" v-model="replyText.text"  :autosize="{minRows:4,maxRows:8}" autocomplete="off"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="replyFlag = false">取 消</el-button>
      <el-button type="primary" @click="sendMail()">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import * as commentApi from "@/api/comment"
import {loginUser} from "@/utils/auth";
import {getEasyUserById} from "@/api/admin";

export default {
  name: "notice",
  data(){
    return{
      idx:0,
      //我的发布
      myCommentList:[],
      //系统通知
      messageTitle:["我发布的","系统消息","评论我的","回复我的","我的消息"],
      systemMail:[{"id":"1","title":"系统通知","createTime":"1970-01-01 00:00:00","text":"这是一个内容"}],
      //评论我的
      CommentList:[{"id":"1","username":"张三","createTime":"1970-01-01 00:00:00","text":"这是一个内容"}],
      total:1,
      //回复我的
      replyList:[{"id":"1","username":"张三","createTime":"1970-01-01 00:00:00","text":"这是一个内容"}],
      params:{
        page:1,
        size:5,
      },
      userNames:{},
      myMailList:[], //我的
      mailDetail:{},
      mailFlag:false,
      replyFlag:false,
      replyText:{},
      isRead:[],
    }
  },

  components: {
    mavonEditor,   //markdown编译器
  },
  methods:{
    selectHandle(index){ //左侧导航栏
      this.idx = index;
      if(index==0){
        this.params = {page:1,size:5,userId:loginUser().id,type:'',field:'create_time'}
        this.getMyCommentList();
      }else if(index==1){
        if(this.isRead[0]>0){ //标记已读
          commentApi.readMail({"id": "1"}).then(res => {})
        }
        this.isRead[0] = 0;
        // console.info(val);
        this.params = {page:1,size:5,userId:"1",to:loginUser().id,field:'create_time'};
        this.getSystemMail();
      }else if(index==2||index==3){
        //标记已读
        if(val!=0){
          var val = this.isRead[index-1];
          this.isRead[index-1] = 0;
          commentApi.flagRead({name:index==2?"_CommentCount":"_ReplyCount","count":val}).then(res=>{});
        }
        this.params = {page:1,size:5,title:loginUser().id,type:index-1,field:'create_time'};
        this.getCommentList();
      }else if(index==4){
        this.params = {page:1,size:10,to:loginUser().id,type:0};
        this.getMyMailList();
      }
    },
    changeSendReply(){ //收件箱和发送的相互切换
      if(this.params.type==1){
        this.params.userId = loginUser().id;
        this.params.to = null;
      }else{
        this.params.userId = null;
        this.params.to = loginUser().id;
      }
      this.chg(1);
    },
    sendMail(){  //发私信
      this.replyText.to = this.mailDetail.userId;
      commentApi.sendMail(this.replyText).then(res=>{
        if(res.data.success){
          this.$message({type:"success",message:"发送成功"});
          this.replyText = {};
          this.replyFlag = false;
        }
      })
    },
    // 弹出邮件详细信息，并标记已读
    mailDetailClick(item){
      // 弹出详情
      this.mailDetail = item;
      this.mailFlag = true;

      //收件箱，标记已读
      if(this.params.type==0) {
        item.read = 1;
        commentApi.readMail({"id": item.id}).then(res => {
        });
      }
    },
    // setType(t){ //设置 params中的 type
    //   this.params.type=t;
    //   this.params.page=1;
    //   this.getMyCommentList();
    // },
    deleteComment(item){  //删除评论/帖子
      this.$confirm('此操作将永久删除该'+(item.type==0?'帖子':'评论')+', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        commentApi.deleteComment({"id":item.id}).then(res=>{
          if(res.data.success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.selectHandle(0);
          }
        })
      })
    },
    deleteMail(item){ //删除消息
      this.$confirm('此操作将永久删除消息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        commentApi.deleteMail({"id":item.id}).then(res=>{
          if(res.data.success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.selectHandle(1);
          }
        })
      })
    },

    //当页数发生变化时执行
    chg(curpage) {
      //更新查询的页数
      this.params.page = curpage;
      //重新查询
      if(this.idx==0){
        this.getMyCommentList();
      }else if(this.idx==1){
        this.getSystemMail();
      }else if(this.idx==2||this.idx==3){
        this.getCommentList();
      }else if(this.idx==4){
        this.getMyMailList();
      }
    },

    getMyCommentList(){ //获取我发布的
      commentApi.commentListSearch(this.params).then( async res=>{
        if(res.data.data){
          var tables = res.data.data.dataList;

          for(var i = 0;i<tables.length;i++){//查询该评论的祖宗帖子
            if(tables[i].type!=0){
              await commentApi.getRootCommentDetail({"id":tables[i].id}).then(res=>{
                if(res.data.data){
                  tables[i].root = res.data.data;
                }else{

                  tables[i].root ={title:"该帖子/评论已被删除",status:1};
                  // console.info(tables[i])
                }

              })
            }


          }
          this.myCommentList = tables;
          this.total = res.data.data.total;
        }

      })
    },
    getSystemMail(){  //获取系统通知

      commentApi.getMailList(this.params).then(res=>{
        if(res.data.success){
          this.systemMail = res.data.data.dataList;
          this.total = res.data.data.total;
          // console.info(this.systemMail)
        }

      })
    },
    getMyMailList(){  //获取我的通知
      commentApi.getMailList(this.params).then(async res=>{
        if(res.data.success){
          var tables = res.data.data.dataList;
          this.total = res.data.data.total;
          var tail = 0;  //MyMail
          //按照时间分类
          var list = [];
          for(var i =0;i<tables.length;i++){
            var va = this.getDay(tables[i].createTime);
            if(tail==0||list[tail-1].date!=va){
              list.push({"date":va,"list":[]});
              tail++;
            }
            list[tail-1].list.push(tables[i]);

          }

          //获取用户名字
          for(i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)

            if(!this.userNames[tables[i].userId]){

              await getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].userId] =  '<span style="color:grey">未知用户</span>';
                }
              });

            }
            if(!this.userNames[tables[i].to]){
              await getEasyUserById({"id":tables[i].to}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].to] =  '<span style="color:grey">未知用户</span>';
                }
              });

            }

          }
          this.myMailList = list;
          // console.info(this.myMailList,list)
        }

      })
    },
    getDay(time){ //天数分类
      var today = new Date();
      time = new Date(time);
      // console.info(time)
      if(this.equalsDays(time,today))return '今天';
      else if(this.equalsDays(this.getLastDay(time,-1),this.getLastDay(today,-1))){
        return '昨天';
      }
      else if(this.equalsDays(this.getLastDay(time,-2),this.getLastDay(today,-2))){
        return '前天';
      }
      else if(this.getLastDay(today,-7).getTime()>=time.getTime()){
        return '一周之内';
      }
      // if(this.getLastDay(today,-365).getTime()>=time.getTime()){
      //   return '一年之内';
      // }
      else return '更早';
    },

    equalsDays(time1,time2){ //是否是同一天
      return time1.getDate()==time2.getDate()&&time1.getMonth()==time2.getMonth()&&time1.getFullYear()==time2.getFullYear();
    },
    getLastDay(time,value){  //之前指定天数
      return new Date(time.getFullYear(),time.getMonth(),time.getDate()+value);
    },
    getCommentList(){
      commentApi.commentListSearch(this.params).then( async res=>{
        if(res.data.data){
           var tables = res.data.data.dataList;

          //获取用户名字
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)

            if(!this.userNames[tables[i].userId]){

              await getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].userId] =  '<span style="color:grey">未知用户</span>';
                }
              });
            }

          }
          if(this.idx==3){  //查询该评论的祖宗帖子
            for(i = 0;i<tables.length;i++){
              await commentApi.getRootCommentDetail({"id":tables[i].id}).then(res=>{
                if(res.data.data){
                  tables[i].root = res.data.data;
                }else{

                  tables[i].root ={title:"该帖子已被删除",status:1};
                  // console.info(tables[i])
                }

              })
            }
          }
          //获取父级评论
          this.CommentList = tables;
          this.total = res.data.data.total;
        }
      })
    },
    getIsNewList(){  //获取未读信息列表
      commentApi.newCommentCountList().then(res=>{
        if(res.data.data){
          this.isRead = res.data.data;
          // console.info(this.isRead);
        }
      })
    },
  },
  created() {

    this.getIsNewList();
    this.userNames[loginUser().id] = "您自己";
    this.selectHandle(0);
  }
}
</script>

<style scoped>
.user-notice .user-menu .el-menu--collapse{
  min-width: 100px;

}
.user-notice{
  position: relative;
  background-color: white;
  width: 90%;
  margin: auto;
  text-align: left;
  vertical-align: top;
}
.user-notice .user-menu{
  display: inline-block;
  min-width: 100px;
  width: 15%;
  /*position: absolute;*/
  /*left: 0px;*/
}
.user-notice  .user-menu-detail{
  background-color: white;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  /*position: absolute;*/
  width: 85%;
  position: relative;
}
.user-notice  .user-menu-detail .user-mail-header{
  padding-right: 20px;
  padding-top: 10px;

}
.user-notice  .user-menu-detail .user-mail-list{
  text-align: left;
}
.user-notice  .user-menu-detail .user-mail-list .user-mail-time{
  margin-left: 10px;
  color: #9f9f9f;
  font-size: 90%;
}

.user-notice .user-menu-detail .notice-mail-list{
  height: 50px;
  font-size: 16px;

  display: block;
  vertical-align: middle;
  border-bottom: 1px solid #e3e6eb;

}
.user-notice .user-menu-detail .notice-mail-list span{
  height: 50px;
  line-height: 50px;
  display: inline-block;
  vertical-align: center;

}
.item {
  margin-top: 10px;
  margin-right: 40px;
}

</style>
<style>
.el-badge__content.is-fixed.is-dot{
  margin-top: 16px;
}
</style>
